<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { Table, TableColumn } from '@/components/Table'
import { Echart } from '@/components/Echart'
import { ElDatePicker } from 'element-plus'
import { formatToDate } from '@/utils/dateUtil'

import { useSearch } from '@/hooks/web/useSearch'
import { useTable } from '@/hooks/web/useTable'
import { ref, reactive, unref, computed, nextTick } from 'vue'
import { getAddUserListApi, getAllPartnerApi } from '@/api/user'
import { useUserStore } from '@/store/modules/user'
import { useI18n } from '@/hooks/web/useI18n'
import dayjs from 'dayjs'
const { t } = useI18n()

const userStore = useUserStore()

const lineOptionsData = computed<any>(() => {
  return {
    xAxis: {
      data: Array.from({ length: 7 }, (_, i) => formatToDate(dayjs().subtract(7 - i, 'day'))),
      boundaryGap: true,
      axisTick: {
        show: true
      }
    },
    grid: {
      left: 20,
      right: 20,
      bottom: 20,
      top: 80,
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      },
      padding: [5, 10]
    },
    yAxis: {
      axisTick: {
        show: false
      }
    },
    legend: {
      data: ['新增用户', '总广告收益', '激励视频收益', '激励广告数'],
      top: 50
    },
    series: [
      {
        name: '新增用户',
        smooth: true,
        type: 'line',
        data: dataList.value.map((item) => {
          return item.newUserCount
        }),
        animationDuration: 2800,
        animationEasing: 'cubicInOut'
      },
      {
        name: '总广告收益',
        smooth: true,
        type: 'line',
        data: dataList.value.map((item) => {
          return (item.todayRevenue * 1).toFixed(2)
        }),
        animationDuration: 2800,
        animationEasing: 'cubicInOut'
      },
      {
        name: '激励视频收益',
        smooth: true,
        type: 'line',
        data: dataList.value.map((item) => {
          return (item.incentiveAdvertisingRevenue * 1).toFixed(2)
        }),
        animationDuration: 2800,
        animationEasing: 'cubicInOut'
      },
      {
        name: '激励广告数',
        smooth: true,
        type: 'line',
        data: dataList.value.map((item) => {
          return item.incentiveAdvertisingCount
        }),
        animationDuration: 2800,
        animationEasing: 'cubicInOut'
      }
    ]
  }
})
const channel = ref<any>()
const getAllPartner = async () => {
  const { data } = await getAllPartnerApi()
  channel.value = data.map((item) => {
    return {
      label: item.userName,
      value: item.id
    }
  })
}
getAllPartner()
// Search
const { searchRegister, searchMethods } = useSearch()
const { getFormData: getSearchFormData, setValues: setSearchFormData } = searchMethods
const schema = computed<FormSchema[]>(() => [
  {
    field: 'date',
    label: '日期筛选',
    component: 'DatePicker',
    formItemProps: {
      slots: {
        default: (formData) => {
          const times = computed({
            get: () => {
              if (formData.startDateStr && formData.endDateStr) {
                return [formData.startDateStr, formData.endDateStr]
              } else {
                return []
              }
            },
            set: (times) => {
              if (times) {
                formData.startDateStr = times[0]
                formData.endDateStr = times[1]
              } else {
                formData.startDateStr = undefined
                formData.endDateStr = undefined
              }
            }
          })
          return (
            <ElDatePicker
              v-model={times.value}
              type="daterange"
              valueFormat="YYYY-MM-DD"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              placeholder="选择日期范围"
            />
          )
        }
      }
    }
  },
  {
    field: 'creator',
    label: '渠道',
    component: 'Select',
    componentProps: {
      options: channel.value
    }
  }
])
//Table
const columns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index'
  },
  {
    field: 'userName',
    label: '合伙人'
  },
  {
    field: 'newUserCount',
    label: '新增用户数'
  },
  {
    field: 'todayRevenue',
    label: '总广告收益',
    slots: {
      default: ({ row }) => {
        return <span>￥{(row.todayRevenue * 1).toFixed(2)}</span>
      }
    }
  },
  {
    field: 'incentiveAdvertisingRevenue',
    label: '激励视频收益',
    slots: {
      default: ({ row }) => {
        return <span>￥{(row.incentiveAdvertisingRevenue * 1).toFixed(2)}</span>
      }
    }
  },
  {
    field: 'incentiveAdvertisingCount',
    label: '激励广告数'
  }
])
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const searchFormData = await getSearchFormData()
    if (JSON.stringify(searchFormData) === '{}') {
      searchFormData.startDateStr = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
      searchFormData.endDateStr = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
    }
    const { data, count } = await getAddUserListApi({
      pageNo: unref(currentPage),
      pageSize: unref(pageSize),
      appId: userStore.getAppId,
      ...searchFormData
    })
    return {
      list: data,
      total: count
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods
// 重置搜索
const onResetSearch = () => {
  setSearchFormData({
    startDateStr: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
    endDateStr: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
    date: undefined
  })
  nextTick(() => {
    getList()
  })
}
</script>

<template>
  <ContentWrap title="新增用户">
    <Search :schema="schema" @search="getList" @reset="onResetSearch" @register="searchRegister" />
    <Echart :options="lineOptionsData" :height="350" />
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="columns"
      :data="dataList"
      row-key="id"
      :loading="loading"
      sortable
      headerAlign="center"
      align="center"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
